<script setup lang="ts">
import {getImage} from "@/utils";
import {ElMessage, type UploadProps} from "element-plus";

// defineProps(["modelValue","width","height"])
defineProps({
    modelValue:{
        type:String,
        required:true
    },
    width:{
        type:Number,
        default:100
    },
    height:{
        type:Number,
        default:100
    }
});
const $emits = defineEmits(["update:model-value"]);

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response
) => {
    $emits("update:model-value",response.url);
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(rawFile.type);
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== "image/png" && rawFile.type !== "image/gif") {
        ElMessage.error('请选择正确的图片格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('最大支持2MB!')
        return false
    }
    return true
}
defineOptions({
    name:"Upload"
})
</script>

<template>
    <el-upload
        class="avatar-uploader"
        action="/yuma/api/upload"
        name="yumaImg"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
        <img :width="width" :height="height" v-if="modelValue" :src="getImage(modelValue)" class="avatar" />
        <el-icon :style="{
            width:width+'px',
            height:height+'px',
        }" v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
</template>

<style scoped lang="less">
.avatar-uploader .avatar {
    display: block;
}
</style>
<style>
.el-table .el-table__cell{
    z-index: auto;
}
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;

    text-align: center;
}
</style>